package com.jfinal.club._admin.teacher;

import java.util.List;
import com.jfinal.club.common.model.Teacher;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;

public class TeacherAdminService {

	private Teacher dao = new Teacher().dao();
	
	public Page<Teacher> paginate(int pageNum) {
		return dao.paginate(pageNum, 10, "select teacher.id,teacher.tname,college.coname,account.nickName ", "from teacher left join college on teacher.coid=college.id left join account on teacher.userid=account.id order by teacher.id desc");
	}
	
	public boolean exists(int teacherId, String name) {
		name = name.toLowerCase().trim();
		String sql = "select id from teacher where tname = ? and id != ? limit 1";
		Integer id = Db.queryInt(sql, name, teacherId);
		return id != null;
	}
	
	public List<Teacher> getAll() {
		List<Teacher> list = dao.find("select * from teacher order by tname");
		return list;
	}
	
	public Ret save(int id, Teacher teacher) {
//		area.setId(id);
		teacher.setTname(teacher.getTname().trim());
		teacher.save();
		return Ret.ok("msg", "创建成功");
	}
	
	public Teacher edit(int id) {
		return dao.findById(id);
	}
	
	public Ret update(Teacher teacher) {
		if (exists(teacher.getId(), teacher.getTname())) {
			return Ret.fail("msg", "教师已经存在");
		}

		teacher.setTname(teacher.getTname().trim());
		teacher.update();
		return Ret.ok("msg", "修改成功");
	}
	
	public Ret delete(int teacherId) {
		dao.deleteById(teacherId);
		return Ret.ok("msg", "教师删除成功");
	}
}
